package com.cn.ccp.webservice.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.cn.ccp.bean.ClassScheduleDetailBean;
import com.cn.ccp.bean.CourseBean;
import com.cn.ccp.bean.CourseContentBean;
import com.cn.ccp.bean.CourseEvaluationBean;
import com.cn.ccp.bean.CourseForumBean;
import com.cn.ccp.bean.CourseNoticeBean;
import com.cn.ccp.bean.CourseOutlineBean;
import com.cn.ccp.bean.CourseSettingBean;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.bean.GradeBean;
import com.cn.ccp.bean.OnlineExamBean;
import com.cn.ccp.bean.ResourseBean;
import com.cn.ccp.bean.SelectedCourse;
import com.cn.ccp.bean.StudentMarkedHistoryBean;
import com.cn.ccp.bean.TermSettingBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.service.classschedule.ClassScheduleDetailService;
import com.cn.ccp.service.classschedule.TermSettingService;
import com.cn.ccp.service.course.CourseContentService;
import com.cn.ccp.service.course.CourseForumService;
import com.cn.ccp.service.course.CourseInvestigationService;
import com.cn.ccp.service.course.CourseService;
import com.cn.ccp.service.course.FilePathService;
import com.cn.ccp.service.course.SelectCourseService;
import com.cn.ccp.service.faculty.GradeService;
import com.cn.ccp.service.onlineEdu.OnlineExamService;
import com.cn.ccp.service.resourse.ResourseService;
import com.cn.ccp.service.system.UserService;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;
import com.cn.ccp.webservice.IWebService;

public class WebService implements IWebService {
	private Logger log = Logger.getLogger(WebService.class);
	
	@Autowired
	private UserService userService;//用户查询service
	@Autowired
	private TermSettingService termSettingService;//课程表设置查询service
	@Autowired
	private GradeService gradeService;
	@Autowired
	private ClassScheduleDetailService classScheduleDetailService;
	@Autowired
	private FilePathService filePathService;
	@Autowired
	private SelectCourseService selectCourseService;
	@Autowired
	private ResourseService resourseService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private CourseContentService courseContentService;
	@Autowired
	private CourseForumService courseForumService;
	@Autowired
	private OnlineExamService onlineExamService;
	@Autowired
	private CourseInvestigationService courseInvestigationService;
	
	private SessionManager manager;
	public WebService(){
		manager = SessionManager.getManager();
		manager.start();
	}
	
	/**
	 * 检查URL
	 * @return
	 * 成功:{"msg":"success"}
	 * 失败:{"msg":"falied"}
	 */
	public String checkUrl(String verCode,String verName){
		return "{\"msg\":\"success\"}";
	}
	
	/**
	 *  是图片
	 * @param path
	 * @return
	 */
	 private boolean isImage(String path){
		 path = path.toLowerCase();
		 if(path.endsWith(".png") || path.endsWith(".jpg"))
			 return true;
		 else
			 return false;
	 }
	

	 private String getHeadImage(UserBean u){
		 if(u.getImage() == null || "".equalsIgnoreCase(u.getImage()))
			 return "";
		try {
			long time = System.currentTimeMillis() ;
			String ext = u.getImage().split("\\.")[1];
			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+u.getId() + File.separator +"head-image"+time+"."+ext);
			des.delete();
			
			FilePathBean fpbean = filePathService.findFilePathById(u.getFile_path_id());
			if(u != null){
				CCPContants.copyFile(fpbean.getPath()+u.getImage(), des.getPath());
				
				u.setHeadImage("tempfile/"+u.getId()+"/"+"head-image"+time+"."+ext);
				return u.getHeadImage(); 
			}
		} catch (Exception e) {
			return "";
		}
		return "";
	 }
	 
	 
	 
	@Override
	public String login(String verCode,String verName,String userLoginName, String password) {
		log.info("---------------userLoginName = "+userLoginName);
		log.info("---------------password = "+password);
		boolean flag = userService.userNameExsit(userLoginName);
		log.info("---------------flag = "+flag);
		if(!flag)
			flag = userService.checkLoginNameIsOk(userLoginName);
		log.info("---------------flag = "+flag);
		StringBuffer buf = new StringBuffer();
		if(!flag){//用户名不存在
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		Object obj = userService.loginForWebservice(userLoginName,password);
		if(obj == null){//查询数据失败，没有响应的用户
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		UserBean u = (UserBean)obj;
		if(u.getStatus() == -1){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		log.info("login success and return value to client..");
		buf.append("{\"msg\":\"success\",\"student\":{");
		buf.append("\"id\":\""+u.getId()+"\",");
		buf.append("\"userName\":\""+u.getUserName()+"\", ");
		buf.append("\"number\":\""+u.getNumber()+"\",\"dormitoryAddress\":\""+u.getDormitoryAddress()+"\",\"email\":\""+u.getEmail()+"\",\"sex\":\""+u.getSex()+"\",\"faculty\":\""+u.getFaculty()+"\",\"specialtyName\":\""+u.getSpecialtyName()+"\",");
//		if( u.getImage() != null  && isImage(u.getImage().trim())){
//			String ext = u.getImage().split("\\.")[1];
//			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+u.getId() + File.separator +"head-image."+ext);
//			if(des.exists()){
//				buf.append("\"image\":\""+"tempfile"+File.separator+u.getId() + File.separator +"head-image."+ext+"\",");
//			}else
//				buf.append("\"image\":\"\",");
//		}else
		buf.append("\"image\":\""+getHeadImage(u)+"\",");
		buf.append("\"gradeName\":\""+u.getGradeName()+"\"");
		buf.append("}}");
		
		UserSession session = manager.createUserSession(u); 
		manager.add(session);
//		log.info(session);
		
		log.info(buf.toString());
		return buf.toString();
	}

	@Override
	public void logout(String verCode,String verName,String userId) {
		log.info(userId);
		manager.getUserSession(userId).setUnValid();
	}

	@Override
	public String querySchedule(String verCode,String verName,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
		}else{
			session.setLastAccessedTime(System.currentTimeMillis());
			if(session.gradeId() != null && !"".equalsIgnoreCase(session.gradeId()) &&  !"-1".equalsIgnoreCase(session.gradeId())){
				buf.append(initSchedule(session.gradeId()));
			}else{//没有课程时
				log.info("user ["+userId+"] has not schedul class.");
				buf.append("{\"msg\":\"success\",\"curDay\":\"[]\",\"week\":\"[]\"}");
			}
		}
		log.info(buf.toString());
		return buf.toString();
	}

	@Override
	public String queryUserById(String verCode,String verName,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		Object obj = null;
		try{
			obj = userService.findById(Integer.parseInt(userId));
		}catch(Exception e){
			log.error("query user detail failed for["+userId+"] :", e);
		}
		
		if(obj == null){//查询数据失败，没有响应的用户
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		UserBean u = (UserBean)obj;
		buf.append(formatUser(u));
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryAllTeachers(String verCode,String verName,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		 List<UserBean> list = selectCourseService.allTeachers();
		 buf.append("[");
		 int len = list.size();
		 UserBean u = null;
		 for(int i=0; i<len; i++){
			 u = list.get(i);
			 buf.append("{\"id\":\""+u.getId()+"\",\"userName\":\""+u.getUserName()+"\"}");
			 if(i != len-1){
				 buf.append(",");
			 }
		 }
		buf.append("]");
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryAllReleaseTimes(String verCode,String verName,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		List<String> list = selectCourseService.allReleaseTimes();
		int len = list.size();
		buf.append("[");
		 for(int i=0; i<len; i++){
			 buf.append("\""+list.get(i)+"\"");
			 if(i != len-1){
				 buf.append(",");
			 }
		 }
		 buf.append("]");
		 log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryAllLevel(String verCode,String verName,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		buf.append("[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\"]");
		return buf.toString();
	}

	@Override
	public String queryCourseTypes(String verCode,String verName,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		
		List<ResourseBean> list = resourseService.pageQueryResourse(Contants.DATA_DICTIONARY_CLASS_TYPE);
		int len = list.size();
		buf.append("[");
		ResourseBean b = null;
		for(int i=0; i<len; i++){
			b = list.get(i);
			buf.append("{\"id\":\""+b.getId()+"\",\"courseTypeName\":\""+b.getName()+"\"}");
			 if(i != len-1){
				 buf.append(",");
			 }
		}
		buf.append("]");
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryLanguageTypes(String verCode,String verName,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		
		List<ResourseBean> list = resourseService.pageQueryResourse(Contants.DATA_DICTIONARY_LANGUAGE_TYPE);
		int len = list.size();
		buf.append("[");
		ResourseBean b = null;
		for(int i=0; i<len; i++){
			b = list.get(i);
			buf.append("{\"id\":\""+b.getId()+"\",\"courseTypeName\":\""+b.getName()+"\"}");
			 if(i != len-1){
				 buf.append(",");
			 }
		}
		buf.append("]");
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryCourseForSelect(String verCode,String verName,int start,int pageSize, String courseName,
			String teachId, String realseTime, String level, String courseType,
			String languageType, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		log.info("------------start =  "+start);   
		log.info("------------courseName =  "+courseName);   
		log.info("------------teachId =  "+teachId);   
		log.info("------------realseTime =  "+realseTime);   
		log.info("------------level =  "+level);   
		log.info("------------courseType =  "+courseType);   
		log.info("------------languageType =  "+languageType);   
		int count = selectCourseService.canSelectedCourse(userId,session.getGrade(),session.getSpecialtyId(),session.getFacultyId(),courseName,courseType,String.valueOf(teachId),String.valueOf(level),realseTime,languageType); 
		List<CourseBean> list = selectCourseService.canSelectedCourse(userId,session.getGrade(),session.getSpecialtyId(),session.getFacultyId(),start, pageSize,courseName,courseType,String.valueOf(teachId),String.valueOf(level),realseTime,languageType);
//		buf.append("{\"msg\":\"success\",\"allcount\":\""+count+"\",\"course\":[");
		int len = list.size();
		log.info("------------len =  "+len);   
		
		CourseSelectListObj listObj = new CourseSelectListObj();
		listObj.setAllcount(count);
		 List<CourseSelectObj> courseList = new ArrayList<CourseSelectObj>();
		 listObj.setCourse(courseList);
		CourseBean b = null;
		for(int i=0; i<len; i++){
			b = list.get(i);
			CourseSelectObj obj = new CourseSelectObj();
			obj.setId(b.getId());
			obj.setCourseName(b.getCourse_name());
			obj.setHighQuality(b.getIs_high_quality());
			
			
//			CCPContants.getFilePath(b.getImage() , getFilePathService(),b.getFile_path_id() , Integer.parseInt(userId) ,false,null);
			if(!b.getImage().equals("book-default.png")){
				if(b.getImage()  != null && !"".equalsIgnoreCase(b.getImage().trim())){
					File sourseFile = null;
					if(b.getFile_path_id() !=  -1)
						sourseFile = new File(getFilePathService().findFilePathById(b.getFile_path_id()).getPath()+b.getImage());
					else
						sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + b.getImage());
					
					File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+ userId + File.separator);
					if(des.mkdir()){
						des.mkdirs();
					}
					des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+ userId  + File.separator +sourseFile.getName());
					CCPContants.copyFile(sourseFile.getPath(), des.getPath());
					b.setImage("tempfile/"+userId+"/"+des.getName());
				}
			}
			obj.setImage(b.getImage());
			obj.setMarks(b.getMarks());
			obj.setLevel(b.getStart_level());
			obj.setTeacherName(b.getTeacherName());
			obj.setStudied(b.isHasSelected());
			obj.setCreateTime(b.getCreate_time());
			obj.setStudingNumber(b.getStudyUsers());
			courseList.add(obj);
		}
		String str =  JSONObject.fromObject(listObj).toString();
		log.info(str);
		
		return str;
	}
	private String getOutlineFilePath(){
		FilePathBean path = getFilePathService().getFlagBean();
		String savePath = CCPContants.SYS_PATH+"files"+File.separator ;
		if(path != null){
			savePath = path.getPath() ;
		}
		return savePath;
	}
	@Override
	public String queryCourseDetailByCourseId(String verCode,String verName,String courseId, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		CourseBean b = getCourseService().getBeanById(courseId);
		CourseDetailJSONObj obj = new CourseDetailJSONObj();
		if(b != null){
			CourseDetailObject detail = new CourseDetailObject();
			obj.setCourse(detail);
			detail.setId(b.getId());
			detail.setCourseName(b.getCourse_name());
//			CCPContants.getFilePath(b.getImage() , getFilePathService(),b.getFile_path_id() , Integer.parseInt(userId) ,false,null);
			if(!b.getImage().equals("book-default.png")){
				if(b.getImage()  != null && !"".equalsIgnoreCase(b.getImage().trim())){
					File sourseFile = null;
					if(b.getFile_path_id() !=  -1)
						sourseFile = new File(getFilePathService().findFilePathById(b.getFile_path_id()).getPath()+b.getImage());
					else
						sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + b.getImage());
					
					File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+ userId + File.separator);
					if(des.mkdir()){
						des.mkdirs();
					}
					des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+ userId  + File.separator +sourseFile.getName());
					CCPContants.copyFile(sourseFile.getPath(), des.getPath());
					b.setImage("tempfile/"+userId+"/"+des.getName());
				}
			}
			detail.setImage(b.getImage());
			detail.setLevel(b.getStart_level());
			detail.setHighQuality(b.getIs_high_quality());
			detail.setTeacherName(b.getTeacherName());
			detail.setCreateTime(b.getCreate_time());
			detail.setMarks(b.getMarks());
			detail.setStudyUsers(b.getStudyUsers());
			detail.setStudied(b.isHasSelected());
			detail.setDescript(b.getDescripte());
			detail.setTeacherDes(b.getTeacherDes());
			
			CourseOutlineBean courseOutLineBean = getCourseService().getOutlineByCourseId(courseId);
			log.info(courseOutLineBean);
			if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null && courseOutLineBean.getOutline().endsWith(".txt")){
				String savePath = getOutlineFilePath();
				savePath += courseOutLineBean.getOutline();
				log.info(savePath);
				BufferedReader reader = null;
				StringBuffer buff = new StringBuffer();
				try {
					reader = new BufferedReader(new FileReader(savePath));
					String text = null;
					while ((text = reader.readLine()) != null){
						 buff.append(text);
						 buff.append(System.getProperty("line.separator"));
					}
					log.info(buff.toString());
					detail.setOutline(buff.toString());
				} catch (IOException e) {
					log.info("read outline failed : ",e);
				} finally{
					try {
						if(reader != null)
							reader.close();
					} catch (IOException e) {
					}
				} 
			}else if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null){//其他文件，使用组件显示
				String savePath = getOutlineFilePath();
				savePath += courseOutLineBean.getOutline();
				String outlinePath  = CCPContants.copyOutline(savePath, courseOutLineBean.getOutline(),Contants.OUTLINE_DERECT);
				log.info("------------outlinePath = "+outlinePath);
//				HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
//				session.setAttribute(CCPContants.OUTLINE_FILE_PATH, courseOutLineBean.getOutline());
				log.info(courseOutLineBean.getOutline());
				detail.setOutline("tempfile/outline/"+courseOutLineBean.getOutline());
			}
			log.info(courseOutLineBean);
			CourseEvaluationBean assessmentBean = getCourseService().getEvaluationByCourseId(courseId);
			log.info(assessmentBean);
			if(assessmentBean != null && assessmentBean.getContents() != null && assessmentBean.getContents().endsWith(".txt")){
				String savePath = getOutlineFilePath();
				savePath += assessmentBean.getContents();
				log.info(savePath);
			
				BufferedReader reader = null;
				StringBuffer buff = new StringBuffer();
				try {
					reader = new BufferedReader(new FileReader(savePath));
					String text = null;
					while ((text = reader.readLine()) != null){
						 buff.append(text);
						 buff.append(System.getProperty("line.separator"));
					}
					log.info( buff.toString());
					detail.setCourseEva(buff.toString());
				} catch (IOException e) {
					log.info("read outline failed : ",e);
				} finally{
					try {
						if(reader != null)
							reader.close();
					} catch (IOException e) {
					}
				}
			}else if(assessmentBean != null && assessmentBean.getContents() != null){
//				showEditEvaluation = false ;
				String savePath = getOutlineFilePath();
				savePath += assessmentBean.getContents();
				String evaluPath  = CCPContants.copyOutline(savePath, assessmentBean.getContents(),Contants.EVALUATION_DERECT);
				log.info("------------evaluPath = "+evaluPath);
//				HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
//				session.setAttribute(CCPContants.EVALUA_FILE_PATH, assessmentBean.getContents());
				log.info( assessmentBean.getContents());
				detail.setCourseEva("tempfile/evaluation/"+assessmentBean.getContents());
			}
			
			
			 
		}else{
			obj.setCourse(null);
		}
		String str =  JSONObject.fromObject(obj).toString();
		log.info(str);
		
		return str;
	}

	@Override
	public String queryCourseChapterList(String verCode,String verName,String courseId, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		List<CourseContentBean> zList = courseContentService.getCourseContentList(courseId);
		CourseChapterObject firstLevelBean = null;//章节bean
		CourseChapterObject secondLevelBean = null;//小节节bean
		CourseChapterListObject obj = new CourseChapterListObject();
		obj.setMsg("success");
		String secondTitle = "";
		for(CourseContentBean b : zList){
			if(firstLevelBean == null){
				firstLevelBean= new CourseChapterObject();
				firstLevelBean.setId(b.getId());
				firstLevelBean.setChapterTitle(b.getChapter_title());
				firstLevelBean.setChapterNumber(b.getChapter_number());
				obj.addCourseChapterObject(firstLevelBean);
			}else{
				if(b.getChapter_number().equalsIgnoreCase(firstLevelBean.getChapterNumber())){//一个章节的内容
					if("0".equalsIgnoreCase(b.getStatus())){//章节下面的具体课程内容
						ChapterObject chapterObject = new ChapterObject();
						chapterObject.setId(b.getId());
						chapterObject.setFileName(b.getSection_file_name());
						chapterObject.setCanBrowse(b.getCan_browse());
						firstLevelBean.addChapters(chapterObject);
					}else{
						if(secondLevelBean == null){//小节bean为空
							secondLevelBean = new CourseChapterObject();
							secondLevelBean.setId(b.getId());
							secondLevelBean.setChapterTitle(b.getChapter_title());
							firstLevelBean.addChild(secondLevelBean);
							
							ChapterObject chapterObject = new ChapterObject();
							chapterObject.setId(b.getId());
							chapterObject.setFileName(b.getSection_file_name());
							chapterObject.setCanBrowse(b.getCan_browse());
							secondLevelBean.addChapters(chapterObject);
							secondTitle = b.getChapter_title();
							continue;
						}
						
						if(secondTitle.equals(b.getChapter_title())){//同一小节的课程内容
							ChapterObject chapterObject = new ChapterObject();
							chapterObject.setId(b.getId());
							chapterObject.setFileName(b.getSection_file_name());
							chapterObject.setCanBrowse(b.getCan_browse());
							secondLevelBean.addChapters(chapterObject);
						}else{//不是一个小节的内容，则创建新的小节
							secondLevelBean = new CourseChapterObject();
							secondLevelBean.setId(b.getId());
							secondLevelBean.setChapterTitle(b.getChapter_title());
							firstLevelBean.addChild(secondLevelBean);
							
							ChapterObject chapterObject = new ChapterObject();
							chapterObject.setId(b.getId());
							chapterObject.setFileName(b.getSection_file_name());
							chapterObject.setCanBrowse(b.getCan_browse());
							secondLevelBean.addChapters(chapterObject);
							secondTitle = b.getChapter_title();;
						}
					}
					
				}else{//不是一个章节的内容，添加一个新的章节目录
					firstLevelBean= new CourseChapterObject();
					firstLevelBean.setId(b.getId());
					firstLevelBean.setChapterTitle(b.getChapter_title());
					firstLevelBean.setChapterNumber(b.getChapter_number());
					obj.addCourseChapterObject(firstLevelBean);
					secondLevelBean = null;
				}
			}
		}
		String str =  JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}
		
	public String queryChapterFile(String verCode,String verName,String chapterId,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(chapterId == null || "".equalsIgnoreCase(chapterId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		CourseContentBean courseContentBean = courseContentService.getCourseContentBean(chapterId);
		int index =  courseContentBean.getSection_file_url().lastIndexOf(".");
		String fileType = courseContentBean.getSection_file_url().substring(index+1,courseContentBean.getSection_file_url().length());
		log.info("-----------fileType = "+fileType);
		String filePath = null;
		
		if("zip".equalsIgnoreCase(fileType)){
			filePath = "tempfile/"+ courseContentBean.getSection_file_name() + "/"+  courseContentBean.getSection_file_name()  + ".htm";
		}else{
			String path = CCPContants.getFilePath(courseContentBean.getSection_file_url() , getFilePathService(),courseContentBean.getFilePathId(),Integer.parseInt(userId));
			log.info("---------path = "+path);
			filePath = "tempfile/"+ userId+"/"+(new File(path)).getName();
		}
		log.info("---------filePath = "+filePath);
		
		buf.append("{\"msg\":\"success\",\"type\":\""+fileType+"\",\"file\":\""+filePath+"\"}");
		log.info(buf);
		return buf.toString();
	}
	
	
	@Override
	public String addOnlineCourse(String verCode,String verName,String courseId, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		boolean flag  = selectCourseService.doAddCourse(courseId, userId, session.getUserName());
		if(flag){
			buf.append("{\"msg\":\"success\"}");
		}else
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryMarkList(String verCode,String verName,String courseId, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		List<StudentMarkedHistoryBean> markedList =  getSelectCourseService().getMarkedList(courseId);
		MarkListObj obj = new MarkListObj();
		List<MarkObj> list = new ArrayList<MarkObj>();
		for(StudentMarkedHistoryBean b :markedList )
			list.add(new MarkObj(b));
		obj.setMarks(list);
		String str = JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}

	@Override
	public String queryForumList(String verCode,String verName,String courseId, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		List<CourseForumBean> list = courseForumService.pageQuery(0, 10000 , userId,courseId);
		CourseForumListObject obj = new CourseForumListObject();
		obj.setMsg("success");
		for(CourseForumBean b: list){
			if(b.getUserId().equals(userId))
				b.setShowEdit(true);
		}
		obj.setForums(list);
		String str = JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}

	@Override
	public String addForum(String verCode,String verName,String userId, String title, String contents,
			String courseId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(title == null || "".equalsIgnoreCase(title)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para title is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		if(contents == null || "".equalsIgnoreCase(contents)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para contents is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		courseForumService.install(courseId ,title, contents, userId ,1);
		buf.append("{\"msg\":\"success\"}");
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryForumReply(String verCode,String verName,String fourmId, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(fourmId == null || "".equalsIgnoreCase(fourmId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para fourmId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		
		List<CourseForumBean> list =  getCourseForumService().replyPageQuery(0, 100000 ,fourmId);
		CourseForumListObject obj = new CourseForumListObject();
		obj.setMsg("success");
		for(CourseForumBean b: list){
			if(b.getUserId().equals(userId))
				b.setShowEdit(true);
			String image = getUserHeadImage(b.getUserId());
			if(image == null)
				b.setUserHeadImage("images/teacher.png");
			else
				b.setUserHeadImage("tempfile/"+b.getUserId()+"/"+image);
		}
		obj.setForums(list);
		String str = JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}

	
	private String getUserHeadImage(String userId){
		File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+ userId);
		String image = null;
		if(des.isDirectory()){
			File[] files = des.listFiles();
			for(File f : files){
				if(f.getName().indexOf("head-image") != -1){
					image = f.getName();
					break;
				}
			}
		}
		log.info(image);
		return image;
	}
	
	
	
	
	@Override
	public String updateForum(String verCode,String verName,String forumId, String title, String contents,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(title == null || "".equalsIgnoreCase(title)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para title is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		if(contents == null || "".equalsIgnoreCase(contents)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para contents is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		if(forumId == null || "".equalsIgnoreCase(forumId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info("The para forumId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		getCourseForumService().update( title,contents, forumId);
		buf.append("{\"msg\":\"success\"}");
		log.info(buf);
		return buf.toString();
	}

	
	/**
	 * 删除帖子
	 * @param forumId：帖子id
	 * @param userId：用户id
	 * @return
	 */
	public String deleteForum(String verCode,String verName,String forumId,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(forumId == null || "".equalsIgnoreCase(forumId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para forumId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		getCourseForumService().deleteContent(forumId);
		buf.append("{\"msg\":\"success\"}");
		log.info(buf);
		return buf.toString();
		
	}
	
	@Override
	public String replyForum(String verCode,String verName,String forumId, String title, String contents,String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(forumId == null || "".equalsIgnoreCase(forumId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para forumId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		if(title == null || "".equalsIgnoreCase(title)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para title is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		 
		
		session.setLastAccessedTime(System.currentTimeMillis());
		
		CourseForumBean bean = getCourseForumService().showBean(forumId);
		getCourseForumService().install(bean.getCourseId() ,bean.getTitle(), contents, userId ,2 ,forumId);
		getCourseForumService().reply(forumId);
		buf.append("{\"msg\":\"success\"}");
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryOlineCourse(String verCode,String verName,int startPage,int pagesize, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("------startPage = "+startPage);
		if(startPage < 0 || startPage > Integer.MAX_VALUE){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para startPage is error, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		log.info("------pagesize = "+pagesize);
		if(pagesize < 0 || pagesize > Integer.MAX_VALUE){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para pagesize is error, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		session.setLastAccessedTime(System.currentTimeMillis());
		List<SelectedCourse>  courseList = selectCourseService.onlineList(userId,startPage, pagesize);
		List<OnlineCourseObj> list = new ArrayList<OnlineCourseObj>();
		for(SelectedCourse b : courseList){
			OnlineCourseObj obj = new OnlineCourseObj(b);
			
			if(!b.getImage().equals("book-default.png")){
				if(b.getImage()  != null && !"".equalsIgnoreCase(b.getImage().trim())){
					File sourseFile = null;
					if(b.getFilePathId() !=  -1)
						sourseFile = new File(getFilePathService().findFilePathById(b.getFilePathId()).getPath()+b.getImage());
					else
						sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + b.getImage());
					
					File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+ userId + File.separator);
					if(des.mkdir()){
						des.mkdirs();
					}
					des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+ userId  + File.separator +sourseFile.getName());
					CCPContants.copyFile(sourseFile.getPath(), des.getPath());
					b.setImage("tempfile/"+userId+"/"+des.getName());
				}
			}
			obj.setImage(b.getImage());
			list.add(obj);
		}
		OnlineListObj obj = new OnlineListObj();
		obj.setAllcount(list.size());
		obj.setCourse(list);
		
		String str = JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}

	@Override
	public String cancelOnlineCourse(String verCode,String verName,String onlineId, String courseId,
			String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(onlineId == null || "".equalsIgnoreCase(onlineId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para onlineId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para title is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		log.info("---------------"+onlineId + " : "+courseId);
		getSelectCourseService().cancelCourse(onlineId,courseId);
		buf.append("{\"msg\":\"success\"}");
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryHomeworkByCourseId(String verCode,String verName,String courseId, String userId) {
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		HomeworkListObj obj = new HomeworkListObj();
		
		List<CourseSettingBean> homeworkList = getSelectCourseService().getCourseSettingByType(courseId, Contants.COURSE_SETTING_TYPE_HOMEWORK,userId);
		obj.setAllcount(homeworkList.size());
		obj.setCourseId(courseId);
//		obj.setCourseName(courseName)
		List<HomeworkObj> list = new ArrayList<HomeworkObj>(homeworkList.size());
		for(CourseSettingBean b : homeworkList){
			list.add(new HomeworkObj(b));
		}
		obj.setHomeworks(list);
		String str = JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}

	
	/**
	 * 根据学生用户id查询该学生的所有需要考试的试题
	 * @param userId
	 * @return
	 *  失败：{"msg":"falied","failedmsg:failedType"}
	 * failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----查询失败
	 * 成功:
	 * 	  {"msg":"success","allcount":"1","tests":[{"id":"id","title":"title","score":"score","hasDone":"1","onlineTaskId","onlineTaskId","courseId":"courseId","courseName":"courseName"}]}
	 *  id:试题id
	 *  title：试题名称
	 *  courseId：课程id 
	 *  score：分数
	 *  hasDone：是否已做标志，1----已做，0----没有做
	 *  onlineTaskId：在线学习课程任务id
	 *  courseName：课程名称
	 *  selectCourseId:在线学习课程任务id
	 */
	public String queryTestByUserId(String verCode,String verName,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			TestListObj obj = new TestListObj();
			List<CourseSettingBean> testList = getSelectCourseService().onlineTestList(userId,0, 1000);
			obj.setAllcount(testList.size());
			List<TestObj> list = new ArrayList<TestObj>(testList.size());
			for(CourseSettingBean b : testList){
				list.add(new TestObj(b));
			}
			obj.setTests(list);
			buf.append(JSONObject.fromObject(obj).toString());
		}catch(Exception e){
			log.error("query test for  ["+userId+"] user  failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	
	public String queryTestDetail(String verCode,String verName,String userId,String testId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------testId = "+testId);
		if(testId == null || "".equalsIgnoreCase(testId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para testId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			TestDetailListObj obj = new TestDetailListObj();
			List<OnlineExamBean> onlineExamList = onlineExamService.getCourseResearch(testId);
			obj.setTestId(testId);
			obj.setAllcount(onlineExamList.size());
			List<TestDetailObj> list = new ArrayList<TestDetailObj>();
			for(OnlineExamBean b : onlineExamList){
				list.add(new TestDetailObj(b));
			}
			obj.setTests(list);
			buf.append(JSONObject.fromObject(obj).toString());
		}catch(Exception e){
			log.error("query test for  ["+testId+"]   failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
		}
		log.info(buf);
		return buf.toString();
		
	}
	
	
	/**
	 * 试题提交
	 * @param userId:用户id
	 * @param testId:试题id
	 * @param selectCourseId:在线学习课程任务id
	 * @param answer:学生提交答案 
	 * @return
	 *  失败：{"msg":"falied","failedmsg:failedType"}
	 * failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----testId为空
	 * 3-----selectCourseId为空
	 * 4-----提交失败
	 * {"msg":"success","score":"80"};
	 * score:考试分数
	 */
	public String commitTest(String verCode,String verName,String userId,String testId,String selectCourseId,String answers){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------testId = "+testId);
		if(testId == null || "".equalsIgnoreCase(testId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para testId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		log.info("---------------selectCourseId = "+selectCourseId);
		if(selectCourseId == null || "".equalsIgnoreCase(selectCourseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para selectCourseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		log.info("---------------answers = "+answers);
		if(selectCourseId == null || "".equalsIgnoreCase(answers)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info("The para answers is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			//检查是否已经做完题目
			int tatol_score = 0 ;
			int reality_score = 0 ;//实际分数
			//已选课程状态： 
			//0--等等审批（对于需要收费的课程来说，在学生选择了该科后状态为0,等等学校领导审批，审批通过后状态进入1，开始学习） 
			//1--正在学习
			//2--已经结业 
			//3--考试未通过
			//4--审批未通过 
			//-1---逻辑删除状态
			int status = 0 ;
			List<OnlineExamBean> onlineExamList = onlineExamService.getCourseResearch(testId);
			
			JSONObject json = JSONObject.fromObject(answers);
			for (int i = 0,n = onlineExamList.size(); i < n; i++) {
				OnlineExamBean bean = onlineExamList.get(i);
				bean.setSelectAnswer(json.get(bean.getIndex()) != null ? json.get(bean.getIndex()).toString() : "" );
				tatol_score = tatol_score + bean.getScore() ;
				if( bean.getAnswer().equalsIgnoreCase(bean.getSelectAnswer()))
					reality_score = reality_score + bean.getScore();
			}
			double hegeFen = tatol_score*0.6 ;
			
			if(reality_score < hegeFen){
				status = 3 ;
			}else{
				status = 2 ;
			}
			courseInvestigationService.commintCourseSetting(userId,testId, selectCourseId,  ""+reality_score, ""+status, onlineExamList);
			buf.append("{\"msg\":\"success\",\"score\":\""+reality_score+"\"}");
		}catch(Exception e){
			log.error("query test for  ["+testId+"]   failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	/**
	 * 查询用户当前正在学习的课程数量
	 * @param userId
	 * @return
	 * 失败：{"msg":"falied","failedmsg:failedType"}
	 * failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----查询失败
	 * 成功：
	 * {"msg":"success","number":"8"};
	 * number：当前正在学习的课程数量
	 */
	public String queryStudingCourseNumber(String verCode,String verName,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			int num = getSelectCourseService().onlineCount(userId);
			buf.append("{\"msg\":\"success\",\"number\":\""+num+"\"}");
		}catch(Exception e){
			log.error("query online couses number failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	/**
	 * 查询学生当天课程表
	 * @param userId
	 * @return
	 * 失败：{"msg":"falied","failedmsg:failedType"}
	 * failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----查询失败
	 * {"msg":"success","detail":"[{scheduleType:2,courseName:语文},{scheduleType:2,courseName:数学}]"};
	 *  scheduleType：作息时间分段类型
	 * 		0----早上
	 *		1----上午
	 *		2----下午
	 *		3----晚上
	 * courseName：课程名称
	 */
	public String queryUserScheduleForToday(String verCode,String verName,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
		}else{
			session.setLastAccessedTime(System.currentTimeMillis());
			if(session.gradeId() != null && !"".equalsIgnoreCase(session.gradeId()) &&  !"-1".equalsIgnoreCase(session.gradeId())){
				buf.append(initTodaySchedule(session.gradeId()));
			}else{//没有课程时
				log.info("user ["+userId+"] has not schedul class.");
				buf.append("{\"msg\":\"success\",\"curDay\":\"[]\",\"week\":\"[]\"}");
			}
		}
		log.info(buf.toString());
		return buf.toString();
	}
	
	
	/**
	 * 根据课程id查询该课程的公告信息
	 * @param verCode
	 * @param verName
	 * @param userId：用户id
	 * @param courseId：课程id
	 * @return
	 * 失败：{"msg":"falied","failedmsg:failedType"}
	 * failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----courseId 为空
	 * 3-----查询失败
	 * 成功:
	 * 
	 */
	public String queryNotiesByCourseId(String verCode,String verName,String userId,String courseId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------courseId = "+courseId);
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
	 
		
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			List<CourseNoticeBean> noticeList = getCourseService().getNoticeByCourseId(courseId);
			CourseNoticeListObj obj = new CourseNoticeListObj();
			List<CourseNoticeObj> notices = new ArrayList<CourseNoticeObj>();
			obj.setNotices(notices);
			for(CourseNoticeBean b : noticeList){
				CourseNoticeObj detailObj = new CourseNoticeObj();
				detailObj.setContents(b.getNotice());
				detailObj.setCreateTime(b.getCreateTime());
				notices.add(detailObj);
			}
			String str = JSONObject.fromObject(obj).toString();
			log.info(str);
			return str;
		}catch(Exception e){
			log.error("query note list failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			return buf.toString();
		}
	}
	
	
	/**
	 * 根据课程编号查询该课程的调查
	 * @param courseId：课程id
	 * @param userId：用户id
	 * @return
	 * 失败：{"msg":"falied","failedmsg:failedType"}
	 *  failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----courseId 为空
	 * 3-----查询失败
	 * 成功：
	 * 
	 */
	public String queryResearchByCourseId(String verCode,String verName,String courseId,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		ListContentsObj obj = new ListContentsObj();
		
		List<CourseSettingBean> homeworkList = getSelectCourseService().getCourseSettingByType(courseId, Contants.COURSE_SETTING_TYPE_INVEST,userId);
		obj.setAllcount(homeworkList.size());
		List<ResearchTitleObj> list = new ArrayList<ResearchTitleObj>(homeworkList.size());
		for(CourseSettingBean b : homeworkList){
			list.add(new ResearchTitleObj(b));
		}
		obj.setContents(list);
		String str = JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}
	
	/**
	 * 根据调查id查询调查的详细信息
	 * @param verCode
	 * @param verName
	 * @param researchId：调查id
	 * @param userId：用户id
	 * @return
	 * 失败：{"msg":"falied","failedmsg:failedType"}
	 *  failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----researchId 为空
	 * 3-----查询失败
	 * 成功
	 * 
	 */
	public String queryResearchDetailById(String verCode,String verName,String researchId,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------researchId = "+researchId);
		if(researchId == null || "".equalsIgnoreCase(researchId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para researchId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			ResearchDetailListObj obj = new ResearchDetailListObj();
			List<OnlineExamBean> onlineExamList = onlineExamService.getCourseResearch(researchId);
			obj.setAllcount(onlineExamList.size());
			List<ResearchDetailObj> list = new ArrayList<ResearchDetailObj>();
			for(OnlineExamBean b : onlineExamList){
				list.add(new ResearchDetailObj(b));
			}
			obj.setContents(list);
			buf.append(JSONObject.fromObject(obj).toString());
		}catch(Exception e){
			log.error("query test for  ["+researchId+"]   failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	
	
	/**
	 * 试题提交
	 * @param userId:用户id
	 * @param researchId:调查id
	 * @param answer:学生提交答案, 
	 * @return
	 *  失败：{"msg":"falied","failedmsg:failedType"}
	 * failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----testId为空
	 * 3-----提交失败
	 */
	public String commitResearch(String verCode,String verName,String userId,String researchId,String answer){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.error("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------researchId = "+researchId);
		if(researchId == null || "".equalsIgnoreCase(researchId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.error("The para researchId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		log.info("---------------answer = "+researchId);
		if(answer == null || "".equalsIgnoreCase(answer)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.error("The para answer is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			List<OnlineExamBean> onlineExamList = onlineExamService.getCourseResearch(researchId);
			JSONObject json = JSONObject.fromObject(answer);
			for (int i = 0,n = onlineExamList.size(); i < n; i++) {
				OnlineExamBean bean = onlineExamList.get(i);
				bean.setSelectAnswer(json.get(bean.getIndex()) != null ? json.get(bean.getIndex()).toString() : "");
			}
			courseInvestigationService.commintInvestigation(researchId,onlineExamList,userId  );
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("query test for  ["+researchId+"]   failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	
	
	public String changeUserImage(String verCode,String verName,String fileByteBuf,String fileType,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(fileByteBuf == null ){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para imageBuf is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		/** 
         * 声明四种I/O流 
         */  
        ByteArrayInputStream fInStream = null;// 文件输入流  
        BufferedInputStream bInStream = null;// 输入缓冲流  
        OutputStream fOutStream = null;// 输出流  
        BufferedOutputStream bOutStream = null;// 输出缓冲流  
		
		try{
			/** 
             * 赋值 
             */  
            // 得到字节数组输入流  
            fInStream = new ByteArrayInputStream(fileByteBuf.getBytes());  
              
            // 得到输入缓冲流  
            bInStream = new BufferedInputStream(fInStream);  
  
            
            String savePath = CCPContants.SYS_PATH+"files"+File.separator + userId + File.separator;
    		
    		FilePathBean filePathBean = filePathService.getFlagBean();
    		if(filePathBean != null){
    			savePath = filePathBean.getPath()+userId+ File.separator ;
    		}
    		File f1 = new File(savePath);
    		log.info(savePath);
    		if (!f1.exists()) {
    			f1.mkdirs();
    		}
            
    		//生成文件名：
			String name = UUID.randomUUID().toString();
			File fileSave = new File(savePath + name +"."+ fileType);
    		
            // 得到输出流  
            fOutStream = new FileOutputStream(fileSave);  
            // 得到输出缓冲流  
            bOutStream = new BufferedOutputStream(fOutStream);  
  
            /** 
             * 循环 
             */  
            int intByte = 512 * 1024;// 缓冲区大小  
            byte[] fileData = new byte[intByte];// 定义一个缓冲区  
            int intIndex = 0;  
            while ((intIndex = bInStream.read(fileData, 0, intByte)) != -1) {  
                bOutStream.write(fileData, 0, intIndex);  
                bOutStream.flush();  
            }  
   
            fileSave = null;  
            if(filePathBean != null){
            	userService.updateUserImage(userId, userId + File.separator +name +"."+ fileType , ""+filePathBean.getId() );
            }else{
            	userService.updateUserImage(userId, userId + File.separator +name +"."+ fileType , "-1");
            }
            String oldImagePath = session.changeHeadImage(userId + File.separator +name +"."+ fileType);
            log.info("oldImagePath = "+oldImagePath);
            File oldFile = null;
            if(filePathBean != null)
            	oldFile = new File(filePathBean.getPath() + oldImagePath);
            else
            	oldFile = new File(CCPContants.SYS_PATH+"files"+File.separator + oldImagePath);
            if(oldFile != null && oldFile.exists()){
            	log.info(oldFile.getAbsolutePath());
            	boolean flag = oldFile.delete();
            	log.info("Delete file ["+flag+"]");
            }
            
		}catch(Exception e){
			log.error("", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info(buf);
			return buf.toString();
		}finally{
            try {  
                if (fInStream != null) {  
                    fInStream.close();// 关闭方法无效？！！！  
                    fInStream = null;  
                }  
                if (bInStream != null) {  
                    bInStream.close();  
                    bInStream = null;  
                }  
                if (fOutStream != null) {  
                    fOutStream.close();  
                    fOutStream = null;  
                }  
                if (bOutStream != null) {  
                    bOutStream.close();  
                    bOutStream = null;  
                }  
            } catch (IOException ee) {  
                log.error ("err：" ,ee);  
            }  
		}
		buf.append("{\"msg\":\"success\"}");
		log.info(buf);
		return buf.toString();
	}
	
	
	
	public String commitCourseMark(String verCode,String verName,String onlieTaskId,String level,String contents,String courseId,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.error("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(onlieTaskId == null || "".equalsIgnoreCase(onlieTaskId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.error("The para onlieTaskId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		int ilevel = -1;
		try{
			ilevel = Integer.parseInt(level);
		}catch(Exception e){}
		
		if(ilevel < 0 || ilevel > 6){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.error("The para level value ["+level+"], please input the right level value.");
			log.info(buf);
			return buf.toString();
		}
		
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.error("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		session.setLastAccessedTime(System.currentTimeMillis());
		getCourseService().doMarkCourse(onlieTaskId, ilevel, contents, courseId,userId);
		
		List<StudentMarkedHistoryBean> markedList =  getSelectCourseService().getMarkedList(courseId);
		MarkListObj obj = new MarkListObj();
		List<MarkObj> list = new ArrayList<MarkObj>();
		for(StudentMarkedHistoryBean b :markedList )
			list.add(new MarkObj(b));
		obj.setMarks(list);
		String str = JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}
	
	
	public String updateUser(String verCode,String verName,String param,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(param == null || "".equalsIgnoreCase(param)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.error("The para param is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		Object obj = null;
		try{
			log.info(userId);
			obj = userService.findById(Integer.parseInt(userId));
		}catch(Exception e){
			log.error("query user detail failed for["+userId+"] :", e);
		}
		
		if(obj == null){//查询数据失败，没有响应的用户
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		UserBean u = (UserBean)obj;
		session.setLastAccessedTime(System.currentTimeMillis());
		log.info(param);
		JSONObject json = JSONObject.fromObject(param);
		
		 SimpleDateFormat  df  =  new  SimpleDateFormat("yyyy-MM-dd");  
		 df.setLenient(false);
			try{
				if(null != json.getString("userName") && !"".equalsIgnoreCase(json.getString("userName")))
					u.setUserName(json.getString("userName"));//用户姓名
			}catch(Exception e){}
			
//			if(null != json.getString("password") && !"".equalsIgnoreCase(json.getString("password")))
//				u.setPassword(json.getString("password"));//密码
			try{	
				if(null != json.getString("homeAddress") && !"".equalsIgnoreCase(json.getString("homeAddress")))
						u.setHomeAddress(json.getString("homeAddress"));//家庭地址
			}catch(Exception e){}
			try{	
				if(null != json.getString("dormitoryAddress") && !"".equalsIgnoreCase(json.getString("dormitoryAddress")))
					u.setDormitoryAddress(json.getString("dormitoryAddress"));//宿舍地址
			}catch(Exception e){}
			try{	
				if(null != json.getString("email") && !"".equalsIgnoreCase(json.getString("email")))
					u.setEmail(json.getString("email"));
			}catch(Exception e){}
			try{	
				if(null != json.getString("phone") && !"".equalsIgnoreCase(json.getString("phone")))
					u.setMobile(json.getString("phone"));//学生电话
			}catch(Exception e){}
			try{	
				if(null != json.getString("birthday") && !"".equalsIgnoreCase(json.getString("birthday"))){
					u.setBirtdate(json.getString("birthday"));//生日
					try {
						df.parse(u.getBirtdate());
					} catch (Exception e) {
						log.info("birthday para is error : ",e);
						buf.append("{\"msg\":\"falied\",\"failedmsg\":\"5\"}");
						log.info(buf.toString());
						return buf.toString();
					}
				}
			}catch(Exception e){}
			try{	
				if(null != json.getString("timeOfEnrollment") && !"".equalsIgnoreCase(json.getString("timeOfEnrollment"))){
					u.setAdmissionTime(json.getString("timeOfEnrollment"));//入学时间 
					try {
						df.parse(u.getAdmissionTime());
					} catch (Exception e) {
						log.info("birthday para is error : ",e);
						buf.append("{\"msg\":\"falied\",\"failedmsg\":\"6\"}");
						log.info(buf.toString());
						return buf.toString();
					}
				}
			}catch(Exception e){}
			try{	
				if(null != json.getString("zipCode") && !"".equalsIgnoreCase(json.getString("zipCode")))
					u.setZipCode(json.getString("zipCode"));//邮编
			}catch(Exception e){}
		try{	
			userService.update(u, false);
			log.info(u);
			buf.append(formatUser(u));
		}catch(Exception e){
			log.error("update user info failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info(buf.toString());
		}
		log.info(buf);
		return buf.toString();
	}
	
	
	/**
	 * 根据用户名和试题id查询用户该试题的分数和各个题的提交答案
	 * @param testId：试题id
	 * @param userId：用户id 
	 * @return
	 * 失败：{"msg":"falied","failedmsg:failedType"}
	 * failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----testId为空
	 * 3-----courseId 课程id为空
	 * 4-----查询失败
	 * 成功：
	 * {"msg":"success","allcount":"1","score":"50","tests":[{"id":"id","number":"number","score":"score","testTitle":"testTitle","type":"type","optionA":"optionA","optionB":"optionB","optionC":"optionC","optionD":"optionD","answer":"answer"}]}
	 *  allcount:试题总数
	 *  testId :试题id
	 *  id:id
	 *  number：试题编号
	 *  score：分数
	 *  testTitle：试题题目
	 *  type：试题类型
	 *  0----选择题
	 *  1----判断题
	 *  optionA：选择题a选项
	 *  optionB：选择题b选项
	 *  optionC：选择题c选项
	 *  optionD：选择题d选项
	 *  answer：参考答案
	 */
	public String queryDoneTestById(String verCode,String verName,String testId,String courseId,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------testId = "+testId);
		if(testId == null || "".equalsIgnoreCase(testId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para testId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------courseId = "+courseId);
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			TestDetailListObj obj = new TestDetailListObj();
			List<OnlineExamBean> onlineExamList = onlineExamService.getStudentSelectCourse(userId, testId , String.valueOf( Contants.COURSE_SETTING_TYPE_TEST));
			obj.setTestId(testId);
			obj.setAllcount(onlineExamList.size());
			SelectedCourse bb = selectCourseService.getSelectedCourseByStuAndCourseId(userId,courseId);
			if(bb != null)
				obj.setScore(bb.getScore());
			List<TestDetailObj> list = new ArrayList<TestDetailObj>();
			for(OnlineExamBean b : onlineExamList){
				list.add(new TestDetailObj(b));
			}
			obj.setTests(list);
			buf.append(JSONObject.fromObject(obj).toString());
		}catch(Exception e){
			log.error("query test for  ["+testId+"]   failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	/**
	 * 根据课程章节id查询该章节文件URL和阅读状态
	 * @param chapterId：章节id
	 * @param userId：用户id
	 * @return
	 * 失败：{"msg":"falied","failedmsg:failedType"}
	 *  failedType：失败类型，定义如下：
	 * 1-----用户没有登录
	 * 2-----参数为空
	 * 成功
	 * {"msg":"success","file":"fileURL",studied:"true"}
	 */
	public String queryOnlineCourseChapterList(String verCode,String verName,String courseId,String onlineTaskId,String userId){
		UserSession session = manager.getUserSession(userId);
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(courseId == null || "".equalsIgnoreCase(courseId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para courseId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		if(onlineTaskId == null || "".equalsIgnoreCase(onlineTaskId)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para onlineTaskId is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		
		session.setLastAccessedTime(System.currentTimeMillis());
		List<CourseContentBean> zList =  getSelectCourseService().getCourseContentsList(courseId,onlineTaskId);
		CourseChapterObject firstLevelBean = null;//章节bean
		CourseChapterObject secondLevelBean = null;//小节节bean
		CourseChapterListObject obj = new CourseChapterListObject();
		obj.setMsg("success");
		String secondTitle = "";
		for(CourseContentBean b : zList){
			if(firstLevelBean == null){
				firstLevelBean= new CourseChapterObject();
				firstLevelBean.setId(b.getId());
				firstLevelBean.setChapterTitle(b.getChapter_title());
				firstLevelBean.setChapterNumber(b.getChapter_number());
				obj.addCourseChapterObject(firstLevelBean);
			}else{
				if(b.getChapter_number().equalsIgnoreCase(firstLevelBean.getChapterNumber())){//一个章节的内容
					if("0".equalsIgnoreCase(b.getStatus())){//章节下面的具体课程内容
						ChapterObject chapterObject = new ChapterObject();
						chapterObject.setId(b.getId());
						chapterObject.setFileName(b.getSection_file_name());
						chapterObject.setStudied(String.valueOf(b.isHaveStudty()));
						firstLevelBean.addChapters(chapterObject);
					}else{
						if(secondLevelBean == null){//小节bean为空
							secondLevelBean = new CourseChapterObject();
							secondLevelBean.setId(b.getId());
							secondLevelBean.setChapterTitle(b.getChapter_title());
							firstLevelBean.addChild(secondLevelBean);
							
							ChapterObject chapterObject = new ChapterObject();
							chapterObject.setId(b.getId());
							chapterObject.setFileName(b.getSection_file_name());
							chapterObject.setStudied(String.valueOf(b.isHaveStudty()));
							secondLevelBean.addChapters(chapterObject);
							secondTitle = b.getChapter_title();
							continue;
						}
						
						if(secondTitle.equals(b.getChapter_title())){//同一小节的课程内容
							ChapterObject chapterObject = new ChapterObject();
							chapterObject.setId(b.getId());
							chapterObject.setFileName(b.getSection_file_name());
							chapterObject.setStudied(String.valueOf(b.isHaveStudty()));
							secondLevelBean.addChapters(chapterObject);
						}else{//不是一个小节的内容，则创建新的小节
							secondLevelBean = new CourseChapterObject();
							secondLevelBean.setId(b.getId());
							secondLevelBean.setChapterTitle(b.getChapter_title());
							firstLevelBean.addChild(secondLevelBean);
							
							ChapterObject chapterObject = new ChapterObject();
							chapterObject.setId(b.getId());
							chapterObject.setFileName(b.getSection_file_name());
							chapterObject.setStudied(String.valueOf(b.isHaveStudty()));
							secondLevelBean.addChapters(chapterObject);
							secondTitle = b.getChapter_title();;
						}
					}
					
				}else{//不是一个章节的内容，添加一个新的章节目录
					firstLevelBean= new CourseChapterObject();
					firstLevelBean.setId(b.getId());
					firstLevelBean.setChapterTitle(b.getChapter_title());
					firstLevelBean.setChapterNumber(b.getChapter_number());
					obj.addCourseChapterObject(firstLevelBean);
					secondLevelBean = null;
				}
			}
		}
		String str =  JSONObject.fromObject(obj).toString();
		log.info(str);
		return str;
	}
	
	
	
	
	
	private String formatUser(UserBean u){
		StringBuffer buf = new StringBuffer();
		buf.append("{\"msg\":\"success\",\"userDetail\":{");
		buf.append("\"id\":\""+u.getId()+"\",");
		buf.append("\"loginName\":\""+u.getLogin_name()+"\", ");
		buf.append("\"userTypeName\":\""+u.getUserTypeName()+"\", ");
		buf.append("\"userName\":\""+u.getUserName()+"\", ");
		buf.append("\"number\":\""+u.getNumber()+"\", ");
		buf.append("\"dormitoryAddress\":\""+u.getDormitoryAddress()+"\", ");
		buf.append("\"homeAddress\":\""+u.getHomeAddress()+"\", ");
		buf.append("\"phone\":\""+u.getMobile()+"\", ");
		buf.append("\"birthday\":\""+u.getBirtdate()+"\", ");
		buf.append("\"timeOfEnrollment\":\""+u.getAdmissionTime()+"\", ");
		buf.append("\"gradeName\":\""+u.getGradeName()+"\", ");
		buf.append("\"email\":\""+u.getEmail()+"\", ");
		buf.append("\"sex\":\""+u.getSex()+"\", ");
		buf.append("\"faculty\":\""+u.getFaculty()+"\", ");
		buf.append("\"specialtyName\":\""+u.getSpecialtyName()+"\", ");
		log.info("user image ["+u.getImage()+"]");
//		if( u.getImage() != null  && !"".equalsIgnoreCase(u.getImage().trim())){
//			String ext = null;
//			try{
//				ext = u.getImage().split("\\.")[1];
//			}catch(Exception e){}
//			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+u.getId() + File.separator +"head-image."+ext);
//			log.info(des.getPath());
//			log.info("des.exists() = "+des.exists());
//			if(des.exists()){
//				buf.append("\"image\":\""+"tempfile"+File.separator+u.getId() + File.separator +"head-image."+ext+"\",");
//			}else{
//				String imagePath = CCPContants.getFilePath(u.getImage() , getFilePathService(),u.getFile_path_id() , u.getId());
//				File file = new File(imagePath);
//				log.info("imagePath= "+imagePath);
//				
//				String headImagePath = file.getParent()+File.separator + "head-image."+ext;
//				log.info("headImagePath= "+headImagePath);
//				file.renameTo(new File(headImagePath));
//				log.info("file.exists() = "+file.exists());
//				if(file.exists())
//					buf.append("\"image\":\""+"tempfile"+File.separator+u.getId() + File.separator +"head-image."+ext+"\",");
//				else
//					buf.append("\"image\":\"\",");
//			}
//		}else
			buf.append("\"image\":\""+getHeadImage(u)+"\",");
		buf.append("\"gradeName\":\""+u.getGradeName()+"\", ");
		buf.append("\"birtdate\":\""+u.getBirtdate()+"\", ");
		buf.append("\"zipCode\":\""+u.getZipCode()+"\", ");
		buf.append("\"admissionTime\":\""+u.getAdmissionTime()+"\", ");
		buf.append("\"descript\":\""+u.getDescript()+"\", ");
		buf.append("\"positional\":\""+u.getPositional()+"\", ");
		buf.append("\"number\":\""+u.getNumber()+"\"}} ");
		log.info(buf);
		return buf.toString();
	}
	
	
	
	/**
	 * 根据年级id查询课程表
	 * @param gradeId
	 * @return
	 */
	private String initSchedule(String gradeId){
		log.info("=============gradeId = "+gradeId);
		Calendar cur = Calendar.getInstance();
		int dayForWeek;
		if(cur.get(Calendar.DAY_OF_WEEK) == 1){  
			 dayForWeek = 7;  
		 }else{  
			 dayForWeek = cur.get(Calendar.DAY_OF_WEEK) - 1;  
		 }  
		int curYear = cur.get(Calendar.YEAR);
		List termSetList = termSettingService.queryTerymByYear(curYear) ;
		StringBuffer buf = new StringBuffer();
		
		if(termSetList == null){
			log.warn("Has been not setting class schudule..");
			return "{\"msg\":\"success\",\"curDay\":\"[]\",\"week\":\"[]\"}";
		}
		int count = termSetList.size();
		TermSettingBean termSettingBean ,curTermSettingBean = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(int i =0; i<count; i++){
			termSettingBean = (TermSettingBean)termSetList.get(i);
			Calendar cal = Calendar.getInstance();
			try {
				cal.setTime(sdf.parse(termSettingBean.getFirstWeekStart()));
			} catch (ParseException e) {
				log.error("format data failed : ", e);
			}
			log.info(termSettingBean);
			int value = cal.compareTo(cur) ;
			log.info("------value = "+value);
			if(value == -1)//cal 比 cur 早
				curTermSettingBean = termSettingBean;
		}
		
		if(curTermSettingBean == null){
			log.warn("Has been not setting class schudule..");
			return "{\"msg\":\"success\",\"curDay\":\"[]\",\"week\":\"[]\"}";
		}
		log.info("-------------"+curTermSettingBean.getId()+":"+gradeId);
		GradeBean gradeBean = (GradeBean)gradeService.findGradeById(Integer.parseInt(gradeId));
//		gradeName = gradeBean.getGradeType();
		List<ClassScheduleDetailBean> allList = classScheduleDetailService.pageQueryForUserByGradeId(gradeId,curTermSettingBean.getId());//返回系统课程表
    	count = allList.size();
    	
    	StringBuffer bufMonday = new StringBuffer();//周一
    	StringBuffer bufTuesday = new StringBuffer();//周二
    	StringBuffer bufWednesday = new StringBuffer();//周三
    	StringBuffer bufThursday = new StringBuffer();//周四
    	StringBuffer bufFriday = new StringBuffer();//周五
    	StringBuffer bufSaturday = new StringBuffer();//周六
    	StringBuffer bufSunday = new StringBuffer();//周日
    	
		for(ClassScheduleDetailBean b : allList){
			switch(b.getWeek()){
				case 1:
					bufMonday.append(formatSchedule(b));
					break;
				case 2:
					bufTuesday.append(formatSchedule(b));
					break;
				case 3:
					bufWednesday.append(formatSchedule(b));
					break;
				case 4:
					bufThursday.append(formatSchedule(b));
					break;
				case 5:
					bufFriday.append(formatSchedule(b));
					break;
				case 6:
					bufSaturday.append(formatSchedule(b));
					break;
				case 7:
					bufSunday.append(formatSchedule(b));
					break;
			}
		}
		buf.append("{\"msg\":\"success\",\"curDay\":[");
		String monday = bufMonday.toString().substring(0,bufMonday.toString().length()-1);
		String tuesday =  bufTuesday.toString().substring(0,bufTuesday.toString().length()-1);
		String wendesday = bufWednesday.toString().substring(0,bufWednesday.toString().length()-1);
		String thursday = bufThursday.toString().substring(0,bufThursday.toString().length()-1);
		String friday = bufFriday.toString().substring(0,bufFriday.toString().length()-1);
		String saturday = bufSaturday.toString().substring(0,bufSaturday.toString().length()-1);
		String sunday = bufSunday.toString().substring(0,bufSunday.toString().length()-1);
		
		switch(dayForWeek){//添加当日课程信息
			case 1:
				buf.append(monday);
				break;
			case 2:
				buf.append(tuesday);
				break;
			case 3:
				buf.append(wendesday);
				break;
			case 4:
				buf.append(thursday);
				break;
			case 5:
				buf.append(friday);
				break;
			case 6:
				buf.append(saturday);
				break;
			case 7:
				buf.append(sunday);
				break;
		}
		buf.append("],");
		buf.append("\"week\":{");//添加周课程详细信息
		buf.append("\"Monday\":["+monday+"],");
		buf.append("\"Tuesday\":["+tuesday+"],");
		buf.append("\"Wednesday\":["+wendesday+"],");
		buf.append("\"Thursday\":["+thursday+"],");
		buf.append("\"Friday\":["+friday.toString()+"],");
		buf.append("\"Saturday\":["+saturday.toString()+"],");
		buf.append("\"Sunday\":["+sunday+"]}}");
//		buf.append("\"week\":\"{")
		
		return buf.toString();
	}
	
	/**
	 * 根据年级id查询课程表
	 * @param gradeId
	 * @return
	 */
	private String initTodaySchedule(String gradeId){
		log.info("=============gradeId = "+gradeId);
		Calendar cur = Calendar.getInstance();
		int dayForWeek;
		if(cur.get(Calendar.DAY_OF_WEEK) == 1){  
			 dayForWeek = 7;  
		 }else{  
			 dayForWeek = cur.get(Calendar.DAY_OF_WEEK) - 1;  
		 }  
		int curYear = cur.get(Calendar.YEAR);
		List termSetList = termSettingService.queryTerymByYear(curYear) ;
		StringBuffer buf = new StringBuffer();
		
		if(termSetList == null){
			log.warn("Has been not setting class schudule..");
			return "{\"msg\":\"success\",\"curDay\":\"[]\",\"week\":\"[]\"}";
		}
		int count = termSetList.size();
		TermSettingBean termSettingBean ,curTermSettingBean = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(int i =0; i<count; i++){
			termSettingBean = (TermSettingBean)termSetList.get(i);
			Calendar cal = Calendar.getInstance();
			try {
				cal.setTime(sdf.parse(termSettingBean.getFirstWeekStart()));
			} catch (ParseException e) {
				log.error("format data failed : ", e);
			}
			log.info(termSettingBean);
			int value = cal.compareTo(cur) ;
			log.info("------value = "+value);
			if(value == -1)//cal 比 cur 早
				curTermSettingBean = termSettingBean;
		}
		
		if(curTermSettingBean == null){
			log.warn("Has been not setting class schudule..");
			return "{\"msg\":\"success\",\"detail\":\"\" }";
		}
		log.info("-------------"+curTermSettingBean.getId()+":"+gradeId);
		GradeBean gradeBean = (GradeBean)gradeService.findGradeById(Integer.parseInt(gradeId));
//		gradeName = gradeBean.getGradeType();
		List<ClassScheduleDetailBean> allList = classScheduleDetailService.pageQueryForUserByGradeId(gradeId,curTermSettingBean.getId());//返回系统课程表
		log.info("-------------"+curTermSettingBean.getId()+":"+gradeId);
    	count = allList.size();
    	log.info("=============:count = "+count);
    	ClassScheduleDetailBean bean;
    	Map<String,Integer> dayMoningList = new HashMap<String,Integer>();//早上课程表list
    	Map<String,Integer> dayNoonList = new HashMap<String,Integer>();//上午课程表list
    	Map<String,Integer> dayAfterNoonList = new HashMap<String,Integer>();//下午课程表list
    	Map<String,Integer> dayNightList = new HashMap<String,Integer>();//晚上课程表list
    	Integer num = null;
    	log.info("=============:dayForWeek = "+dayForWeek);
    	for(int i=0; i<count; i++){
    		bean = allList.get(i);
    		if(bean.getSubjects().equalsIgnoreCase(Contants.SCHEDULE_CLASS_SUBJECT_INIT))
    			continue;
    		log.info(bean.getWeek()+ "----------"+bean.getSubjects());
    		if(bean.getWeek() == dayForWeek){
    			
    			log.info("----------"+bean.getSubjects());
    			switch(bean.getScheduleType()){
    				case Contants.SCHEDULE_TYPE_MORNING://早上
    					num = dayMoningList.get(bean.getSubjects());
    					if(num == null)
    						dayMoningList.put(bean.getSubjects(), Integer.valueOf(1));
    					else
    						dayMoningList.put(bean.getSubjects(), num.intValue()+1);	
    					break;
    				case Contants.SCHEDULE_TYPE_FORENOON://上午
    					num = dayNoonList.get(bean.getSubjects());
    					if(num == null)
    						dayNoonList.put(bean.getSubjects(), Integer.valueOf(1));
    					else
    						dayNoonList.put(bean.getSubjects(), num.intValue()+1);	
    					break;
    				case Contants.SCHEDULE_TYPE_AFTERNOON://下午
    					num = dayAfterNoonList.get(bean.getSubjects());
    					if(num == null)
    						dayAfterNoonList.put(bean.getSubjects(), Integer.valueOf(1));
    					else
    						dayAfterNoonList.put(bean.getSubjects(), num.intValue()+1);	
    					break;
    				case Contants.SCHEDULE_TYPE_NIGHT://晚上
    					num = dayNightList.get(bean.getSubjects());
    					if(num == null)
    						dayNightList.put(bean.getSubjects(), Integer.valueOf(1));
    					else
    						dayNightList.put(bean.getSubjects(), num.intValue()+1);	
    					break;
    			}
    		}
    	}
    	
    	ScheduleTodayListObj obj = new ScheduleTodayListObj();
    	List<ScheduleTodayObj> detail = new ArrayList<ScheduleTodayObj>();
    	obj.setDetail(detail);
    	
    	if(dayMoningList.size() > 0){
    		Iterator it = dayMoningList.entrySet().iterator();
    		while (it.hasNext()) {
	    		Map.Entry entry = (Map.Entry) it.next();
	    		Object key = entry.getKey();
	    		Object value = entry.getValue();
	    		detail.add(new ScheduleTodayObj("0",key.toString(),value.toString()));
    		} 
    	}
    	
    	 if(dayNoonList.size()> 0){
     		Iterator it = dayNoonList.entrySet().iterator();
     		while (it.hasNext()) {
 	    		Map.Entry entry = (Map.Entry) it.next();
 	    		Object key = entry.getKey();
 	    		Object value = entry.getValue();
 	    		detail.add(new ScheduleTodayObj("1",key.toString(),value.toString()));
     		} 
    	 }
    	
    	 if(dayAfterNoonList.size()> 0){
     		Iterator it = dayAfterNoonList.entrySet().iterator();
     		while (it.hasNext()) {
 	    		Map.Entry entry = (Map.Entry) it.next();
 	    		Object key = entry.getKey();
 	    		Object value = entry.getValue();
 	    		detail.add(new ScheduleTodayObj("2",key.toString(),value.toString()));
     		} 
    	 }
    	 
    	 if(dayNightList.size()> 0){
     		Iterator it = dayNightList.entrySet().iterator();
     		while (it.hasNext()) {
 	    		Map.Entry entry = (Map.Entry) it.next();
 	    		Object key = entry.getKey();
 	    		Object value = entry.getValue();
 	    		detail.add(new ScheduleTodayObj("3",key.toString(),value.toString()));
     		} 
    	 }
    	 return JSONObject.fromObject(obj).toString();
	}
	
	
	
	/**
	 * 格式化课程表信息
	 * @param b
	 * @return
	 */
	private String formatSchedule(ClassScheduleDetailBean b){
		StringBuffer buf = new StringBuffer();
		if(!Contants.SCHEDULE_CLASS_SUBJECT_INIT.equalsIgnoreCase(b.getSubjects())){//设置了课程表内容
			buf.append("{\"subject\":\""+b.getSubjects()+"\",\"address\":\""+b.getClassAddress()+"\",\"startTime\":\""+b.getStartTime()+"\",\"endTime\":\""+b.getEndTime()+"\",\"startWeek\":\""+b.getStartWeek()+"\",\"endWeek\":\""+b.getEndWeek()+"\",\"scheduleType\":\""+b.getScheduleType()+"\"},");
		}else{
			buf.append("{\"subject\":\"\",\"address\":\"\",\"startTime\":\"\",\"endTime\":\"\",\"startWeek\":\"\",\"endWeek\":\"\",\"scheduleType\":\""+b.getScheduleType()+"\"},");
		}
		return buf.toString();
	}
	
	
	
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public TermSettingService getTermSettingService() {
		return termSettingService;
	}

	public void setTermSettingService(TermSettingService termSettingService) {
		this.termSettingService = termSettingService;
	}
	public GradeService getGradeService() {
		return gradeService;
	}
	public void setGradeService(GradeService gradeService) {
		this.gradeService = gradeService;
	}
	public ClassScheduleDetailService getClassScheduleDetailService() {
		return classScheduleDetailService;
	}
	public void setClassScheduleDetailService(
			ClassScheduleDetailService classScheduleDetailService) {
		this.classScheduleDetailService = classScheduleDetailService;
	}

	public FilePathService getFilePathService() {
		return filePathService;
	}

	public void setFilePathService(FilePathService filePathService) {
		this.filePathService = filePathService;
	}

	public SelectCourseService getSelectCourseService() {
		return selectCourseService;
	}

	public void setSelectCourseService(SelectCourseService selectCourseService) {
		this.selectCourseService = selectCourseService;
	}

	public ResourseService getResourseService() {
		return resourseService;
	}

	public void setResourseService(ResourseService resourseService) {
		this.resourseService = resourseService;
	}

	public CourseService getCourseService() {
		return courseService;
	}

	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	public CourseContentService getCourseContentService() {
		return courseContentService;
	}

	public void setCourseContentService(CourseContentService courseContentService) {
		this.courseContentService = courseContentService;
	}

	public CourseForumService getCourseForumService() {
		return courseForumService;
	}

	public void setCourseForumService(CourseForumService courseForumService) {
		this.courseForumService = courseForumService;
	}

	public void setOnlineExamService(OnlineExamService onlineExamService) {
		this.onlineExamService = onlineExamService;
	}

	public void setCourseInvestigationService(
			CourseInvestigationService courseInvestigationService) {
		this.courseInvestigationService = courseInvestigationService;
	}
	
	
	
}
